package net.ib.mtalk.ui.buddy.suggestion;

import com.google.protobuf.micro.InvalidProtocolBufferMicroException;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Common.SuggestionReason;
import net.ib.mntalk.protocol.Common.SuggestionReasonKnowsOption;
import net.ib.mntalk.protocol.Common.UUIDMsg;
import net.ib.mntalk.protocol.Session.AddContactsReq;
import net.ib.mntalk.protocol.Session.GetSuggestionsReq;
import net.ib.mntalk.protocol.Session.GetSuggestionsVersionReq;
import net.ib.mtalk.R;
import net.ib.mtalk.base.BaseFragmentActivity;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.database.DatabaseContract.BuddyTable;
import net.ib.mtalk.database.DatabaseContract.SuggestionTable;
import net.ib.mtalk.database.helper.NotifyingAsyncQueryHandler;
import net.ib.mtalk.global.GlobalPreferences;
import net.ib.mtalk.ui.dialog.DialogListItem;
import net.ib.mtalk.ui.dialog.DialogMenu;
import net.ib.mtalk.ui.widget.QuickAction;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.text.style.BulletSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class BuddySuggestionListActivity extends BaseFragmentActivity{

	private static Context mContext;
	private static BuddySuggestionController mUiController;
	private int downloadCount_total = 0; 
	private int downloadCount = 0; 
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case HandlerMsgConst.HANDLER_GET_SUGGESTIONS_SUCCESS:
				Toast.makeText(mContext, "HANDLER_GET_SUGGESTIONS_SUCCESS", Toast.LENGTH_SHORT).show();
				downloadCount = (Integer) msg.obj;
				break;
			case HandlerMsgConst.HANDLER_GET_SUGGESTIONS_FAIL:
				Toast.makeText(mContext, "HANDLER_GET_SUGGESTIONS_FAIL", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_UNKNOWN_ERROR:
				Toast.makeText(mContext, "HANDLER_UNKNOWN_ERROR", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_ADD_BUDDY_SUCCESS:
				Toast.makeText(mContext, "HANDLER_ADD_BUDDY_SUCCESS", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_ADD_BUDDY_FAIL:
				Toast.makeText(mContext, "HANDLER_ADD_BUDDY_FAIL", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_SET_SUGGESTION_SUCCESS:
				String name = (String) msg.obj;
				Toast.makeText(mContext, name + getString(R.string.suggestion_deleted), Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_SET_SUGGESTION_FAIL:
				Toast.makeText(mContext, "HANDLER_SET_SUGGESTION_FAIL", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_GET_SUGGESTION_VERSION_SUCCESS:
				Toast.makeText(mContext, "HANDLER_GET_SUGGESTIONS_SUCCESS", Toast.LENGTH_SHORT).show();
				if(GlobalPreferences.getSuggestionVersion() != (Long) msg.obj){
					getSuggestions((Long) msg.obj);
				}
				break;
			case HandlerMsgConst.HANDLER_GET_SUGGESTION_VERSION_FAIL:
				Toast.makeText(mContext, "HANDLER_GET_SUGGESTIONS_FAIL", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_PROFILE_DOWNLOAD_SUCCESS:
				Toast.makeText(mContext, "HANDLER_SUGGESTION_DOWNLOAD_SUCCESS", Toast.LENGTH_SHORT).show();
				downloadCount ++;
				if(downloadCount_total == downloadCount){
					BuddySuggestionFragment list = new BuddySuggestionFragment();
					fm.beginTransaction().replace(R.id.buddy_suggestion_list, list)
					.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
					.commit();
				}
				break;
			default:
				break;
			}
		};
	};
	private static final int QUERY_SUGGESTION = 0;
	private FragmentManager fm;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_buddy_suggestion_list);
		
		mContext = this;
		mUiController = new BuddySuggestionController(mContext, mHandler);
		
		fm = getSupportFragmentManager();
		
		if(savedInstanceState == null) {
			BuddySuggestionFragment list = new BuddySuggestionFragment();
			fm.beginTransaction().add(R.id.buddy_suggestion_list, list).commit();
		}
		getSuggestionVersion();
	}
	
	private void getSuggestionVersion() {
		GetSuggestionsVersionReq getSuggestionsVersionReq = new GetSuggestionsVersionReq();
		getSuggestionsVersionReq.setType(Common.USER_OBJ);
		mUiController.getSuggestionVersion(getSuggestionsVersionReq);
	}

	private void getSuggestions(long version) {
		GetSuggestionsReq getSuggestionsReq = new GetSuggestionsReq();
		getSuggestionsReq.setRange(new Common.SuggestionIdSliceRange().setAscending(true).setMaxCount(100));
		getSuggestionsReq.setType(Common.USER_OBJ);
		mUiController.getSuggestions(getSuggestionsReq, version);
	}

	public static class BuddySuggestionFragment extends ListFragment {

		private CursorAdapter mAdapter;
		private NotifyingAsyncQueryHandler queryHandler;
		
		@Override
		public void onActivityCreated(Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);
			setHasOptionsMenu(true);
			
			mAdapter = new BuddySuggestionCursorAdapter(getActivity(), null, 0, mUiController);
			
			ListView listView = getListView();
			listView.setDivider(getResources().getDrawable(R.drawable.inbox_divider));
			listView.setDividerHeight(1);
			listView.setFastScrollEnabled(true);
			listView.setScrollingCacheEnabled(false);
			listView.setAdapter(mAdapter);
			
			queryHandler = new NotifyingAsyncQueryHandler(getActivity().getParent().getContentResolver(), onQueryReturn);
			String select = "((" + SuggestionTable.KEY_SUGGESTION_UUID_MSB + " NOTNULL) AND ("
					+ SuggestionTable.KEY_SUGGESTION_UUID_LSB + " NOTNULL) AND " + SuggestionTable.KEY_STATUS_TYPE + "='1')";
			String sortOrder = SuggestionTable.KEY_SCORE+ " COLLATE LOCALIZED DESC";
			queryHandler.startQuery(QUERY_SUGGESTION, null, SuggestionTable.CONTENT_URI, SuggestionTable.PROJECTION, select, null, sortOrder);
			
			ListView lv = getListView();
			lv.setOnItemLongClickListener(new OnItemLongClickListener() {
				@Override
				public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
					final long msb = mAdapter.getCursor().getLong(mAdapter.getCursor().getColumnIndexOrThrow(SuggestionTable.KEY_SUGGESTION_UUID_MSB));
					final long lsb = mAdapter.getCursor().getLong(mAdapter.getCursor().getColumnIndexOrThrow(SuggestionTable.KEY_SUGGESTION_UUID_LSB));
					SuggestionReasonKnowsOption option = null;
					try {
						option = SuggestionReasonKnowsOption.parseFrom(mAdapter.getCursor().getBlob(mAdapter.getCursor().getColumnIndexOrThrow(SuggestionTable.KEY_KNOWS_OPTIONS)));
					} catch (InvalidProtocolBufferMicroException e) {
						e.printStackTrace();
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					}
					final String name = option.getKnowsProfile().getName().getDisplayName();
					getActivity().showDialog(1);
					//makeDialog(msb, lsb, name);
					AlertDialog.Builder  builder = new AlertDialog.Builder(getActivity().getParent());
					builder.setMessage(R.string.suggestion_confirm_delete);
					builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							mUiController.deleteSuggestion(msb, lsb, name);
						}
					});
					builder.setNegativeButton(R.string.no, null);
					builder.show();
					return true;
				}

			});
		}
		
		/**
		 * 현재 Suggestion 변화 상태를 Observing 한다. 
		 */
		ContentObserver mSuggestionObserver = new ContentObserver(new Handler()) {
			public void onChange(boolean selfChange) {
				String select = "((" + SuggestionTable.KEY_SUGGESTION_UUID_MSB + " NOTNULL) AND ("
						+ SuggestionTable.KEY_SUGGESTION_UUID_LSB + " NOTNULL) AND " + SuggestionTable.KEY_STATUS_TYPE + "='1')";
				String sortOrder = SuggestionTable.KEY_SCORE+ " COLLATE LOCALIZED DESC";
				queryHandler.startQuery(QUERY_SUGGESTION, null, SuggestionTable.CONTENT_URI, SuggestionTable.PROJECTION, select, null, sortOrder);
			};
		};
		
		@Override
		public void onListItemClick(ListView l, View v, int position, long id) {
			super.onListItemClick(l, v, position, id);
		}
		
		@Override
		public void onResume() {
			super.onResume();
			getActivity().getParent().getContentResolver().registerContentObserver(SuggestionTable.CONTENT_URI, true, mSuggestionObserver);
			mSuggestionObserver.onChange(true);
		}
		
		@Override
		public void onPause() {
			super.onPause();
			getActivity().getParent().getContentResolver().unregisterContentObserver(mSuggestionObserver);
		}
		
		NotifyingAsyncQueryHandler.AsyncQueryListener onQueryReturn = new NotifyingAsyncQueryHandler.AsyncQueryListener() {
			@Override
			public void onQueryComplete(int token, Object cookie, Cursor cursor) {
				switch (token){
				case QUERY_SUGGESTION:
					getActivity().getParent().getParent().startManagingCursor(cursor);
					mAdapter.changeCursor(cursor);
					break;
				}
			}

			@Override
			public void onInsertComplete(int token, Object cookie, Uri uri) {
				
			}

			@Override
			public void onUpdateComplete(int token, Object cookie, int result) {
				
			}

			@Override
			public void onDeleteComplete(int token, Object cookie, int result) {
				
			}
		};
	}
	
	
	public static void makeDialog(final long msb, final long lsb,
			final String name) {
		AlertDialog.Builder builder = new AlertDialog.Builder(mContext.getApplicationContext());
		builder.setMessage(R.string.suggestion_confirm_delete);
		builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				mUiController.deleteSuggestion(msb, lsb, name);
			}
		});
		builder.setNegativeButton(R.string.no, null);
		builder.show();
	}
}
